import 'dart:async';
import 'dart:developer';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:pinput/pinput.dart';
import 'package:sports_new/base/base_controller.dart';
import 'package:sports_new/controller/live/ali_live_logic.dart';
import 'package:sports_new/controller/live/live_message_logic.dart';
import 'package:sports_new/entity/live/live_detail_entity.dart';
import 'package:sports_new/entity/live/live_chat_info.dart';
import 'package:sports_new/server/api/live_api.dart';
import 'package:sports_new/server/ws/ws_manager.dart';
import 'package:sports_new/utils/ali_message.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/utils.dart';
import '../../entity/match/expert_views_entity.dart';
import '../../entity/live/live_chat_entity.dart';
import '../../entity/match/match_live_entity.dart';
import '../../entity/other/user_info_entity.dart';
import '../../server/api/expert_api.dart';
import '../../server/api/user_api.dart';
import '../../utils/toast_utils.dart';
import '../../utils/widget_utils.dart';

class LiveChatLogic extends BaseController{
  String _matchId = "${Get.arguments}";
  late int sportsId;
  LiveChatInfo? chatInfo;
  PlanEntity? plan;
  bool _showPlan = true;
  final Rx<String> _str = "".obs;
  MatchLiveEntity? _roomInfo;
  LiveDetailEntity? liveInfo;
  StreamSubscription? _stream;
  bool inScroll = false;
  UserInfoEntity? _userStore;

  String get str => _str.value;
  MatchLiveEntity? get roomInfo => _roomInfo;
  String get matchId => _matchId;
  bool get showPlan => _showPlan;
  UserInfoEntity? get userStore => _userStore;

  set userStore(UserInfoEntity? value) {
    try {
      _userStore = value;
    }catch(e){
      log(e.toString());
    }
    update();
  }
  set showPlan(bool value) {
    _showPlan = value;
    update();
  }
  set matchId(String value) {
    _matchId = value;
    update();
  }
  set roomInfo(MatchLiveEntity? value) {
    _roomInfo = value;
    update();
  }

  set str(String value) {
    _str.value = value;
  }

  final textController = TextEditingController();
  late FocusNode focus = FocusNode();

  @override
  void onReady() async{
    await getLogic();
    getPlan();
    super.onReady();
  }

  Future getLogic() async{
    await Future.delayed(const Duration(milliseconds: 200));
    try {
      AliLiveLogic live = Get.find<AliLiveLogic>(tag: matchId);
      sportsId = live.sportsId;
      roomInfo = live.roomInfo;
      liveInfo = await LiveApi.getLiveDetail(roomInfo?.roomId);
    } catch (e) {
      log(e.toString());
    }
    update();
  }

  Future getData() async{
    chatInfo = await LiveApi.getChatInfo(roomInfo?.roomId);
    update();
  }

  Future getPlan() async{
    var row = await ExpertApi.getLivePlan(
        matchId, roomInfo?.expertId, sportsId, 1, 10
    );
    if(row.recommend.hasValue){
      plan = row.recommend!.first;
    }else if(row.other.hasValue){
      plan = row.other!.first;
    }
    update();
  }

  Future sendChat({String? text}) async{
    await LiveApi.sendChat(text ?? str, roomInfo?.roomId);
  }

  Future toFocus() async{
    await User.needLogin(() {
      Utils.onEvent('hpzb',params: {'hpzb':4});
        AliMessage().enterGroup(
          liveInfo?.chatGroupId ?? ""
        );
        userStore = User.info;
    }
    );
    if (liveInfo?.isFocus == 0) {
      final result = await UserApi.focus(
        expertId: liveInfo?.expertId
      );
      if (result == 200) {
        LiveDetailEntity? entity = await LiveApi.getLiveDetail(roomInfo?.roomId);
        if(entity != null){
          liveInfo = entity;
          ToastUtils.show('关注成功');
        }else{
          ToastUtils.show('关注失败');
        }
        update();
      }
    } else {
      final r = await WidgetUtils.alertQuery('确认不再关注？');
      if (r == true) {
        final result = await UserApi.unFocus(
          expertId: liveInfo?.expertId
        );
        if (result == 200) {
          LiveDetailEntity? entity = await LiveApi.getLiveDetail(roomInfo?.roomId);
          if(entity != null){
            liveInfo = entity;
            ToastUtils.show('取关成功');
          }else{
            ToastUtils.show('取关失败');
          }
          update();
        }
      }
    }
  }

  Future getFocus() async{
    if(liveInfo == null) return;
    liveInfo = await LiveApi.getLiveDetail(roomInfo?.roomId);
    update();
  }

  @override
  void getRefresh() async{
    liveInfo = null;
    update();
    await getLogic();
    await getPlan();
    getData();
    super.getRefresh();
  }

  @override
  void dispose() {
    _stream?.cancel();
    super.dispose();
  }
}
